//
//  ActionDetail.m
//  nova
//
//  Created by user on 11/06/12.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "ActionDetail.h"
#define myAppDelegate (novaAppDelegate *) [[UIApplication sharedApplication] delegate]

@implementation ActionDetail
@synthesize action;
//@synthesize navigationItem;
// The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
/*
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization.
    }
    return self;
}
*/


-(IBAction) cancelChanges{
	 [self.view removeFromSuperview];
}


-(IBAction) saveAction{
	//UIAlertView *exitingWithSave = [[UIAlertView alloc] initWithTitle:@"Action changed. Save it?" message:@"Do you wish to save the changes made to this action?" delegate:self cancelButtonTitle:@"No"  otherButtonTitles:nil];
	//[exitingWithSave addButtonWithTitle:@"Yes"];
	//[exitingWithSave show];
	//[exitingWithSave ]
	//SavePopup *savePopup = [[SavePopup alloc] init];
	//[savePopup setModalTransitionStyle:UIModalTransitionStylePartialCurl];
	//[self presentModalViewController:savePopup animated:YES];
	
	[action setActionDescription:[[txtDescription text] retain]];
	
	DataContext *context = [[DataContext alloc] init];
	if([action isNew] && [action changed]){
			[context executeQuery:[action getInsertString]];
			[[myAppDelegate getProject] insertNewAction:action];
	}else if([action changed]){
		[context executeQuery:[action getUpdateString]];
	}
}

-(void) alertView : (UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
	//UIAlertView *exitingWithSave = [[UIAlertView alloc] initWithTitle:@"ZAnother?" message:@"Another?" delegate:self cancelButtonTitle:@"No"  otherButtonTitles:nil];
	//[exitingWithSave addButtonWithTitle:@"Yes"];
	//[exitingWithSave show];
	if(buttonIndex == 1)
	{
		DataContext *context = [[DataContext alloc] init];
		if([action isNew] && [action changed]){
			@try {
				[context executeQuery:[action getInsertString]];
				[[myAppDelegate getProject] insertNewAction:action];
			}
			@catch (NSException * e) {
				UIAlertView *exitingWithSave = [[UIAlertView alloc] initWithTitle:@"Error saving to database." message:@"There was an error saving this action. Please restart the aplication!" delegate:nil cancelButtonTitle:@"Ok"  otherButtonTitles:nil];
			}
		}else if([action changed]){
			[context executeQuery:[action getUpdateString]];
		}
		//[self.view removeFromSuperview];
		[context dealloc];
		//[action dealloc];
		//action = nil;
		context = nil;		
	}
}

-(IBAction) textFieldValueChanged : (id) sender{
		[action setChanged:YES];
		/* if(sender == txtOwner){
		 return; 
		 }else if(sender == txtPriority){
		 return;
		 }else if(sender == txtFinish){
		 return;
		 }else if(sender == txtBaselineFinish){
		 return;
		 }else if(sender == txtDescription){
			 [action setActionDescription:[txtDescription text]];
		 }*/
}

-(IBAction) btFinishDateClick : (id) sender{
	DatePicker *datePicker = [[DatePicker alloc] initWithNibName:@"DatePicker" bundle:[NSBundle mainBundle]];
	[datePicker setTargetObject:action];
	[datePicker setTargetTimeSelector:[action getSetFinishSelector]];
	[datePicker setTargetButton:(UIButton *)sender];
	[self.view addSubview:datePicker.view];
}

-(IBAction) btBaseLineFinishDateClick : (id) sender{
	DatePicker *datePicker = [[DatePicker alloc] initWithNibName:@"DatePicker" bundle:[NSBundle mainBundle]];
	[datePicker setTargetObject:action];
	[datePicker setTargetTimeSelector:[action getSetBaselineFinishSelector]];
	[datePicker setTargetButton:(UIButton *)sender];
	[self.view addSubview:datePicker.view];
}

-(IBAction) btOwnerClick : (id) sender{
	NSLog(@"Entrou aki");
	[sender resignFirstResponder];
}

-(IBAction) btPriorityClick : (id) sender{
	NSLog(@"Entrou aki");
	[sender resignFirstResponder];
}

-(IBAction) openDetails{
	[scroll setScrollEnabled:YES];
	if(commentListView != nil){
		[commentListView.view removeFromSuperview];
		[commentListView dealloc];
		commentListView = nil;
	}	
}

-(IBAction) openComments{
	if(commentListView == nil){
		commentListView = [[ProjectCommentList alloc] initWithNibName:@"ProjectCommentList" bundle:[NSBundle mainBundle]];
	}
	[commentListView setAction:action];
	[commentListView setCommentList : [action commentList]];
	//[self.view addSubview :commentList.view ];
	[scroll setScrollEnabled:NO];
	[scroll addSubview:commentListView.view];
	
}
-(IBAction) openHistory{
	if(historyListView == nil){
		historyListView = [[ProjectHistoryList alloc] initWithNibName:@"ProjectHistoryList" bundle:[NSBundle mainBundle]];
	}
	[historyListView setHistoryArray:[action historyList]];
	//[self.view addSubview :commentList.view ];
	[scroll setScrollEnabled:NO];
	[scroll addSubview:historyListView.view];
	

}

-(IBAction) textFieldReturn : (id) sender{
	//[txtOwner resignFirstResponder];
	//[txtPriority resignFirstResponder];
	//[txtFinish resignFirstResponder];
	//[txtBaselineFinish resignFirstResponder];
	[txtDescription resignFirstResponder];
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	[super viewDidLoad];
	
	[scroll
	 setContentSize:CGSizeMake(320,
							   686)];
	[self initObjects]; 
	backgroundView.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"background.jpg"]];
	}

-(void) initObjects{
	
	[lblProject setText: [[myAppDelegate getProject] getProjectName]];
	[lblDateCreated setText: [Library getLocalizedDateString : [action getDateCreated]]];
	
	if(![action isNew]){
	
		[txtDescription setText: [action getActionDescription]];
		
		txtDescription.text = [action getActionDescription];
	
		
		[btFinish setTitle:[Library getLocalizedDateString : [action getFinish]] forState: UIControlStateNormal ];
		NSLog([Library getLocalizedDateString : [action getFinish]]);
		[btBaselineFinish  setTitle: [Library getLocalizedDateString : [action getBaseLineFinish]] forState: UIControlStateNormal ];	
		[btOwner setTitle:[action getOwner] forState: UIControlStateNormal ];
	
		NSDate *now = [[NSDate alloc] init];
		double nowTimeInterval = [now timeIntervalSince1970];
	
		double totalProgress =  ([action getDateCreated] + nowTimeInterval * 100) / [action getBaseLineFinish];	
		if (totalProgress > 100){
			lblProgressLabel.text = @"100";
		}
		else{
			lblProgressLabel.text = [NSString stringWithFormat:@"%.2f",totalProgress];
		}
	
		[progress setProgress:(([action getDateCreated] + nowTimeInterval) / [action getBaseLineFinish])];
		
		[btPriority setTitle:[[action actionPriority] getPriorityDescription] forState: UIControlStateNormal];
	}else{
		
		lblProgressLabel.text = @"0";

		[progress setProgress:0];
	}
}

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations.
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc. that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void) viewWillAppear:(BOOL)animated{
	[super viewWillAppear:animated];
	[scroll setScrollEnabled:YES];
}

- (void)viewWillDisappear:(BOOL)animated {
    [self saveAction];
	[super viewWillDisappear:animated];
	
}



- (void)dealloc {
    [super dealloc];
}


@end
